package com.ticket.sass.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.mapper.OrderCommodityDetailMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.OrderCommodityDetailEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-07
 */
@Service
public class OrderCommodityDetailServiceImpl extends ServiceImpl<OrderCommodityDetailMapper, OrderCommodityDetailEntity> implements BaseService<OrderCommodityDetailEntity> {
    // 方法一：根据订单ID列表返回卖品ID列表
    public List<Long> findCommodityIdsByOrderIds(List<Long> orderIds) {
        if (orderIds.size() == 0){
            return new ArrayList<>();
        }
        
        QueryWrapper<OrderCommodityDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT commodity_id")
            .in("order_commodity_id", orderIds);
        return this.baseMapper.selectObjs(queryWrapper);
    }
    
    // 方法二：根据订单ID列表返回Map，一对多关系，一个订单对应多个实体，订单ID和实体列表的映射
    public Map<Long, List<OrderCommodityDetailEntity>> findOrderCommodityDetailsByOrderIds(List<Long> orderIds) {
        if (orderIds.isEmpty()){
            return new HashMap<>();
        }
        
        QueryWrapper<OrderCommodityDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("order_commodity_id", "commodity_id", "sku_id", "sku_info", "price", "num")
            .in("order_commodity_id", orderIds);
        List<OrderCommodityDetailEntity> entities = this.baseMapper.selectList(queryWrapper);
        
        Map<Long, List<OrderCommodityDetailEntity>> resultMap = new HashMap<>();
        for (OrderCommodityDetailEntity entity : entities) {
            Long orderId = entity.getOrderCommodityId();
            if (!resultMap.containsKey(orderId)) {
                resultMap.put(orderId, new ArrayList<>());
            }
            resultMap.get(orderId).add(entity);
        }
        return resultMap;
    }
    
    public List<OrderCommodityDetailEntity> findOrderCommodityDetailsByOrderId(Long orderId) {

        
        QueryWrapper<OrderCommodityDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_commodity_id", orderId);
        List<OrderCommodityDetailEntity> entities = this.baseMapper.selectList(queryWrapper);
        
        List<OrderCommodityDetailEntity> resultList = new ArrayList<>();
        for (OrderCommodityDetailEntity entity : entities) {
            resultList.add(entity);
        }
        return resultList;
    }
}
